<template>
  <div class="license-agreement">
    <ContentContainer
      :show-pagination="false"
      :show-footer="false"
      :loading="loading"
      inner
      :refresh="false">
      <div class="flex flex-col gap-y-6">
        <div class="flex flex-col gap-y-2">
          <span class="title">证书模式</span>
          <a-radio-group v-model="source">
            <a-radio :value="2">
              <div class="flex items-center">
                <span>系统托管</span>
                <a-tag color="#00AB41" class="system-tag">自动续期</a-tag>
              </div>
            </a-radio>
            <a-radio :value="1">手动上传</a-radio>
          </a-radio-group>
        </div>

        <ManualUpload v-if="source === 1" />
        <SystemHosting v-else :cname="cname" @reload="getLicenseInfo" />
        <div class="flex flex-col">
          <span class="title">协议选择</span>
          <span class="subtitle">
            HTTP 端口：{{ httpPortList.join(',') }}，HTTPS 端口：{{
              httpsPortList.join(',')
            }}
          </span>
          <a-radio-group
            v-model="protocol"
            class="protocol-radio"
            @click="
              (e: any) => {
                if (e.target?.className === 'change-port') {
                  e.preventDefault()
                }
              }
            ">
            <a-radio
              v-for="(item, index) in protocolArray"
              :key="item.value"
              :value="item.value">
              <template #radio="{ checked }">
                <div
                  class="custom-radio-card"
                  :class="{ 'custom-radio-card-checked': checked }">
                  <span class="title">{{ item.title }}</span>

                  <span class="subtitle text-xs!">
                    {{ `${item.subtitle}` }}
                    <template v-if="index === 2">
                      ，目标端口：
                      <span>
                        <a-input-number
                          v-show="showPortInput"
                          ref="portInputRef"
                          v-model="port"
                          :precision="0"
                          :max-length="5"
                          :min="0"
                          :max="65535"
                          hide-button
                          class="w-15! px-2! h-6!"
                          @press-enter="handleBlur"
                          @blur="handleBlur">
                        </a-input-number>
                        <span
                          v-if="!showPortInput"
                          class="change-port"
                          @click="show"
                          >{{ port }}</span
                        >
                      </span>
                    </template>
                  </span>
                </div>
              </template>
            </a-radio>
          </a-radio-group>
        </div>
        <a-button type="primary" class="w-22" @click="() => handleSave()">
          保存配置
        </a-button>
      </div>
    </ContentContainer>

    <ContentContainer
      :show-pagination="false"
      :show-footer="false"
      inner
      :refresh="false">
      <template #header>
        <div class="flex flex-col">
          <span class="title font-bold text-1">支持协议版本</span>
        </div>
      </template>
      <div class="flex gap-x-6">
        <div v-for="item in tlsArray" :key="item" class="flex gap-x-2">
          <i-icons-success />
          {{ item }}
        </div>
      </div>
    </ContentContainer>
    <UploadLicense v-model="visible" @reload="getLicenseInfo"></UploadLicense>
  </div>
</template>
<script setup lang="ts">
import type { SiteLicenseCname, SiteLicenseModel } from '@/apis/model/License'
import { getApiConfigCdnPortApi } from '@/apis/modules/config'
import { getApiSiteCertApi, updateApiSiteCertApi } from '@/apis/modules/license'
import type { InputInstance } from '@arco-design/web-vue'
import { Loading } from 'tdesign-vue-next'
import ManualUpload from './components/ManualUpload.vue'
import SystemHosting from './components/SystemHosting.vue'
import UploadLicense from './components/UploadLicense.vue'
const { visible, open: openUpload } = usePopup()

const loading = ref(false)
const route = useRoute()
const source = ref(2)
const protocol = ref(1)
const port = ref(443)
const httpPortList = ref<string[]>([])
const httpsPortList = ref<string[]>([])
const portInputRef = ref<InputInstance[]>([])
const licenseInfo = ref<SiteLicenseModel>({})
const cname = ref<SiteLicenseCname>()
const siteId = computed(() => route.params.id as string)
const showPortInput = ref(false)
const protocolArray = [
  {
    title: '仅HTTP',
    subtitle: '只能通过 HTTP 请求站点',
    value: 1
  },
  {
    title: 'HTTP+HTTPS',
    subtitle: '可同时通过 HTTP 和 HTTPS 请求站点',
    value: 2
  },
  {
    title: '强制HTTPS',
    subtitle: '将所有 HTTP 请求重定向到 HTTPS',
    value: 3
  }
]

const tlsArray = ['TLSv1.0', 'TLSv1.1', 'TLSv1.2', 'TLSv1.3']

const show = async () => {
  showPortInput.value = true
  await nextTick()
  portInputRef.value![0].focus()
}
const handleBlur = () => {
  if (!port.value) {
    port.value = licenseInfo.value?.site_cert?.force_https_port ?? 443
  }
  showPortInput.value = false
}
const getLicenseInfo = (updateSource: boolean = true) => {
  Loading.value = true
  getApiSiteCertApi({ id: siteId.value })
    .then((res) => {
      licenseInfo.value = res

      if (updateSource) {
        source.value = res.site_cert?.source ?? 1
      }
      port.value = res?.site_cert?.force_https_port ?? 443
      cname.value = res.cname
      if (
        res.site_cert?.http_status === 1 &&
        res.site_cert?.https_status === 1
      ) {
        protocol.value = 2
      } else if (res.site_cert?.http_status == 1) {
        protocol.value = 1
      } else {
        protocol.value = 3
      }
    })
    .finally(() => {
      loading.value = false
    })
}
const getPortConf = () => {
  getApiConfigCdnPortApi({ with_default_ports: true }).then((res) => {
    httpPortList.value = res.http ?? []
    httpsPortList.value = res.https ?? []
  })
}
const handleSave = () => {
  const data: any = {
    id: siteId.value,
    source: source.value,
    http_status: protocol.value !== 3 ? 1 : 2,
    https_status: protocol.value !== 1 ? 1 : 2,
    force_https_port: port.value
  }
  return updateApiSiteCertApi(data).then(() => {
    ToastUtils.success('保存成功')
    getLicenseInfo()
  })
}
watchEffect(() => {
  getLicenseInfo()
})

provide(licenseInfoKey, licenseInfo)
provide(uploadLicenseKey, openUpload)

onMounted(() => {
  getPortConf()
})
</script>

<style lang="less">
.license-agreement {
  @apply flex flex-col gap-y-4;
  .system-tag {
    height: 20px;
    border-radius: 8px 1px;
    padding: 2px 6px;
    margin-left: 4px;
  }

  .protocol-radio {
    @apply grid grid-rows-1 grid-cols-3 mt-2;
    .arco-radio {
      padding-left: 0;
    }
  }
  .title {
    @apply text-2 leading-22px text-sm;
  }
  .subtitle {
    @apply text-5 leading-5 text-xs;
  }
  .custom-radio-card {
    display: flex;
    flex-direction: column;
    row-gap: 4px;
    flex: 1;
    height: 72px;
    border-radius: 4px;
    border: 1px solid var(---color-border-4, #dfe2e5);
    padding: 12px 16px;
    &-checked {
      border: 1px solid var(---primary-6, #165dff);
      background: var(---primary-1, #e8f3ff);
    }
  }
  .change-port {
    @apply text-primary cursor-pointer r;
  }
}
</style>
